package com.sjtu.service;

import com.sjtu.dao.model.TaskInfo;
import com.sjtu.service.cache.TaskInfoCache;
import com.sjtu.service.ref.CronExpression;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * nerine
 * 1/29/2020
 */
@Slf4j
@Component
public class JobAllocator {
    @Autowired
    private TaskInfoCache taskInfoCache;
    @Autowired
    private ScheduledThreadPoolExecutor jobAllocateThread;
    @Autowired
    private TaskSendService taskSendService;

    public void allocate(String systemId) {
        ConcurrentMap<String, TaskInfo> taskInfoMap = taskInfoCache.getTaskCache().get(systemId);
        for (TaskInfo taskInfo : taskInfoMap.values()) {
            String cron = taskInfo.getCron();
            try {
                CronExpression cronExpression = new CronExpression(cron);
                Date now = new Date();
                Date nextTriggerTime = cronExpression.getNextValidTimeAfter(now);
                jobAllocateThread.schedule(() -> {
                    try {
                        taskSendService.sendTask(taskInfo);
                    } catch (Exception e) {
                        log.error("error occurred when begin schedule job: ", e);
                    }
                }, nextTriggerTime.getTime() - now.getTime(), TimeUnit.MILLISECONDS);
            } catch (ParseException e) {
                log.error(
                        String.format("cron expression parse error, task_id: %s, cron: %s", taskInfo.getIdTaskInfo(), cron),
                        e);
            }
        }
    }
 }
